<template>
  <div class="item-select-dlg dialog-box">
    <el-form
      ref="formSelectStudentAIRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="90px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormSelectStudentAI()" @reset="resetFormSelectStudentAI">
        <el-form-item label="学生姓名">
          <el-input
            class="filter-item"
            v-model="formFilter.studentNameFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="所属年级">
          <el-select
            class="filter-item"
            v-model="formFilter.gradeIdFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="gradeIdFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in gradeIdFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="经验等级">
          <el-select
            class="filter-item"
            v-model="formFilter.experienceLevelFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="experienceLevelFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in experienceLevelFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属校区">
          <dept-select
            class="filter-item"
            v-model="formFilter.schoolIdFilter"
            placeholder=""
          />
        </el-form-item>
        <template #operation>
          <el-button type="primary" @click="onSubmit" :size="layoutStore.defaultFormItemSize">
            确定
          </el-button>
        </template>
      </filter-box>
    </el-form>
    <table-box
      ref="student"
      class="main-box"
      :data="studentWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((studentWidgetCurrentPage - 1) * studentWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="false"
       :hasSearchString="true"
      @sort-change="studentWidget.onSortChange"
      @refresh="studentWidget.refreshTable()"
      @radio-select-change="onSelectChange"
    >
      <vxe-column title="" fixed="left" type="radio" align="center" :width="80" />
      <vxe-column title="学生姓名" field="studentName" />
      <vxe-column title="所属校区" field="schoolIdDictMap.name" />
      <vxe-column title="所属年级" field="gradeIdDictMap.name" />
      <vxe-column title="经验等级" field="experienceLevelDictMap.name" />
      <vxe-column title="注册时间" field="registerTime">
        <template v-slot="scope">
          <span>{{formatDateByStatsType(scope.row.registerTime, 'day')}}</span>
        </template>
      </vxe-column>
      <template slot="empty">
        <div class="table-empty unified-font">
          <img src="@/assets/img/empty.png">
          <span>暂无数据</span>
        </div>
      </template>
      <!-- 分页 -->
      <template #pagination>
        <el-row type="flex" justify="end" style="margin-top: 10px;">
          <el-pagination
            :total="studentWidgetTotalCount"
            :current-page="studentWidgetCurrentPage"
            :page-size="studentWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="studentWidget.onCurrentPageChange"
            @size-change="studentWidget.onPageSizeChange">
          </el-pagination>
        </el-row>
      </template>
    </table-box>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formSelectStudentAI',
};
</script>

<script setup lang="ts">
import { DialogProp } from '@/components/Dialog/types';
import * as validateRules from '@/common/utils/validate';
import { VxeColumn, VxeTable } from 'vxe-table';
import { ANY_OBJECT } from '@/types/generic';
import { DictData, DictionaryBase } from '@/common/staticDict/types';
import { ElMessage, ElMessageBox, UploadFile } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useCommon } from '@/common/hooks/useCommon';
import { useLayoutStore, useStaticDictStore } from '@/store';
import { useDownload } from '@/common/hooks/useDownload';
import { useDropdown } from '@/common/hooks/useDropdown';
import { DropdownOptions, ListData } from '@/common/types/list';
import { useTable } from '@/common/hooks/useTable';
import { TableOptions } from '@/common/types/pagination';
import { useUpload } from '@/common/hooks/useUpload';
import { useUploadWidget } from '@/common/hooks/useUploadWidget';
import { DictionaryController } from '@/api/system';
import { treeDataTranslate, findItemFromList, findTreeNodePath, findTreeNode, stringCase } from '@/common/utils';
import { StudentData } from '@/api/generated/studentController';
import { SysDeptData } from '@/api/generated/sysDeptController';
import { StudentController, SysDeptController } from '@/api/generated';
import DeptSelect from '@/components/DeptSelect/index.vue';
import UserSelect from '@/components/UserSelect/index.vue';

const router = useRouter();
const route = useRoute();
const layoutStore = useLayoutStore();
const { downloadFile } = useDownload();
const { getUploadHeaders, getUploadActionUrl, fileListToJson, parseUploadData, getPictureList } = useUpload();
const { 
  Delete,
  Search,
  Edit,
  Plus,
  Refresh,
  Picture,
  Dialog,
  mainContextHeight,
  clientHeight,
  checkPermCodeExist,
  parseParams,
  parseArrayParams,
  formatDateByStatsType,
  getDateRangeFilter,
} = useCommon();
// 静态字典
const { staticDict: StaticDict } = useStaticDictStore();

const pps = withDefaults(
  defineProps<{
    modelValue: StudentData[];
    subPage?: number | string | boolean;
    props: {
      label: string;
      value: string;
    };
    // 当使用Dialog.show弹出组件时，须定义该prop属性，以便对dialog进行回调
    dialog?: DialogProp<ANY_OBJECT[]>;
  }>(),
  {
    modelValue: () => [],
    props: () => {
      return {
        label: 'name',
        value: 'id',
      };
    },
    dialog: undefined,
  },
);
// 选中数据
const dialogSelectItems = ref<StudentData>();
const formFilter = reactive({
  // 学生姓名
  studentNameFilter: undefined,
  // 所属年级
  gradeIdFilter: undefined,
  // 经验等级
  experienceLevelFilter: undefined,
  // 所属校区
  schoolIdFilter: undefined,
});
const formFilterCopy = reactive({
  // 学生姓名
  studentNameFilter: undefined,
  // 所属年级
  gradeIdFilter: undefined,
  // 经验等级
  experienceLevelFilter: undefined,
  // 所属校区
  schoolIdFilter: undefined,
});

const onCancel = () => {
  if (pps.dialog) {
    pps.dialog.cancel();
  }
};

const onSubmit = () => {
  if (pps.dialog) {
    pps.dialog.submit(dialogSelectItems.value);
  }
};

/**
 * 重置过滤值
 */
const resetFormSelectStudentAI = () => {
  formFilter.studentNameFilter = undefined;
  formFilterCopy.studentNameFilter = undefined;
  formFilter.gradeIdFilter = undefined;
  formFilterCopy.gradeIdFilter = undefined;
  formFilter.experienceLevelFilter = undefined;
  formFilterCopy.experienceLevelFilter = undefined;
  formFilter.schoolIdFilter = undefined;
  formFilterCopy.schoolIdFilter = undefined;
  refreshFormSelectStudentAI();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormSelectStudentAI();
};
/**
 * 表格组件数据获取函数，返回Promise
 */
const loadStudentWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
  };
  return new Promise((resolve, reject) => {
    const searchString = student.value ? student.value.getSearchString() : undefined;
    if (searchString && searchString !== '') {
      if (params.studentDtoFilter == null) params.studentDtoFilter = {};
      params.studentDtoFilter.searchString = searchString;
    }
    StudentController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
      nextTick(() => {
        setTableSelectRow();
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadStudentVerify = () => {
  formFilterCopy.studentNameFilter = formFilter.studentNameFilter;
  formFilterCopy.gradeIdFilter = formFilter.gradeIdFilter;
  formFilterCopy.experienceLevelFilter = formFilter.experienceLevelFilter;
  formFilterCopy.schoolIdFilter = formFilter.schoolIdFilter;
  return true;
};
// 表格组件表格组件参数
const studentOptions: TableOptions<StudentData> = {
  loadTableData: loadStudentWidgetData,
  verifyTableParameter: loadStudentVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const student = ref();
const studentWidget = useTable(studentOptions);
const {
  dataList: studentWidgetDataList,
  currentPage: studentWidgetCurrentPage,
  pageSize: studentWidgetPageSize,
  totalCount: studentWidgetTotalCount,
} = studentWidget;
/**
 * 所属年级下拉数据获取函数
 */
const loadGradeIdFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'Grade', itemIdType: 'Integer' }).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 所属年级配置参数
const gradeIdFilterOptions: DropdownOptions<DictData> = {
  loadData: loadGradeIdFilterDropdownList,
  isTree: false,
};
// 所属年级下拉组件
const gradeIdFilterWidget = useDropdown(gradeIdFilterOptions);
const { dropdownList: gradeIdFilterWidgetDropdownList } = gradeIdFilterWidget
/**
 * 经验等级下拉数据获取函数
 */
const loadExperienceLevelFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'ExpLevel', itemIdType: 'Integer' }).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 经验等级配置参数
const experienceLevelFilterOptions: DropdownOptions<DictData> = {
  loadData: loadExperienceLevelFilterDropdownList,
  isTree: false,
};
// 经验等级下拉组件
const experienceLevelFilterWidget = useDropdown(experienceLevelFilterOptions);
const { dropdownList: experienceLevelFilterWidgetDropdownList } = experienceLevelFilterWidget
const setTableSelectRow = () => {
  if (student.value == null || !Array.isArray(studentWidget.dataList.value))
    return;
  setTimeout(() => {
    let selectRow = findItemFromList(
      studentWidget.dataList.value,
      (dialogSelectItems.value || {})[pps.props.value],
      pps.props.value,
    );
    student.value.getTableImpl().setRadioRow(selectRow);
  }, 50);
};
const refreshFormSelectStudentAI = () => {
  // 重新获取数据组件的数据
  studentWidget.refreshTable();
};
const onSelectChange = (row?: StudentData) => {
  dialogSelectItems.value = row;
};

const formInit = () => {
  gradeIdFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  experienceLevelFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormSelectStudentAI();
};

onMounted(() => {
  if (Array.isArray(pps.modelValue) && pps.modelValue.length > 0) {
    dialogSelectItems.value = {
      ...pps.modelValue[0],
    };
  }
  formInit();
});
</script>

<style scoped>
.main-box {
  flex-grow: 1;
}
</style>
